package cn.com.nes.site.service.workOrder.impl;

import cn.com.nes.common.em.WorkOrderRecordDescEnum;
import cn.com.nes.common.util.MapUtils;
import cn.com.nes.common.util.OssImagePathUtils;
import cn.com.nes.common.util.XzqhUtils;
import cn.com.nes.common.util.id.AgentIdEnum;
import cn.com.nes.common.util.id.AgentIdUtils;
import cn.com.nes.mybatis.agent.ope.entity.IsWorkOrderEquipmentInfo;
import cn.com.nes.mybatis.agent.ope.entity.IsWorkOrderInfo;
import cn.com.nes.mybatis.agent.ope.entity.IsWorkOrderRecord;
import cn.com.nes.mybatis.agent.ope.mapper.IsEquipmentFaultInfoMapper;
import cn.com.nes.mybatis.agent.ope.mapper.IsWorkOrderEquipmentInfoMapper;
import cn.com.nes.mybatis.agent.ope.mapper.IsWorkOrderInfoMapper;
import cn.com.nes.mybatis.agent.ope.mapper.IsWorkOrderRecordMapper;
import cn.com.nes.mybatis.agent.system.mapper.TUserMapper;
import cn.com.nes.mybatis.callcenter.mapper.TXzqhMapper;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.entity.dto.fault.EquipmentFaultInfoListDto;
import cn.com.nes.site.entity.vo.fault.EquipmentFaultInfoListVo;
import cn.com.nes.site.entity.vo.workOrder.FaultWorkOrderVo;
import cn.com.nes.site.entity.vo.workOrder.RepairWorkOrderVo;
import cn.com.nes.site.module.service.monitor.EquipmentInfoService;
import cn.com.nes.site.service.system.message.MessageInfoService;
import cn.com.nes.site.service.workOrder.RepairWorkOrderService;
import cn.com.nes.site.service.workOrder.dto.ImageDto;
import cn.com.nes.site.service.workOrder.dto.RepairWorkOrderDto;
import cn.com.nes.site.service.workOrder.dto.UsedPartDto;
import cn.com.nes.site.service.workOrder.dto.WorkOrderFollowUpRecordDto;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static cn.com.nes.common.util.Globals.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: ShenWei
 * @Date: 2024/03/08/9:23
 */
@Deprecated
@Service
public class RepairWorkOrderServiceImpl implements RepairWorkOrderService {
    private static final String USER_TYPE_IS_ADMIN = "04";  // 用户类型为管理员
    private static final String AREA_CODE_IS_CHINA = "86";  // 区号是全国
    private static final String sjly = "agent"; // 数据来源

    @Resource
    TUserMapper tUserMapper;

    @Resource
    TXzqhMapper tXzqhMapper;

    @Resource
    IsWorkOrderInfoMapper repairWorkOrderMapper;

    @Resource
    IsEquipmentFaultInfoMapper equipmentFaultInfoMapper;

    @Resource
    IsWorkOrderEquipmentInfoMapper workOrderIsEquipmentInfoMapper;

    @Resource
    IsWorkOrderRecordMapper isWorkOrderRecordMapper;

    @Autowired
    EquipmentInfoService equipmentInfoService;

    @Autowired
    MessageInfoService messageInfoService;

    /**
     * 查询维修工单列表
     *
     * @param vo
     * @return
     * @throws Exception
     */
    @Override
    public PageData getRepairWorkOrderInfoList(RepairWorkOrderVo vo) throws Exception {
        if (null != vo.getRepairResult() && vo.getRepairResult().equals("1")) {//未修好
            vo.setAuditStatusNotEquals("1");
        }
        //获取当前用户的人员类别
        String userType = tUserMapper.getUserTypeByUserId(vo.getUserId());
        //不为管理员时 - 需要判断当前登录用户id是否和工单主表中的userid或者maintain_id相等
        if (!userType.equals(USER_TYPE_IS_ADMIN)) {
            vo.setIsNotAdmin("1");
        }

        String areaCode = vo.getAreaCode();
        if (StrUtil.isNotEmpty(areaCode) && !AREA_CODE_IS_CHINA.equals(areaCode)) {
            //根据行政区划,查找行政区划级别
            String areaCodeLevel = tXzqhMapper.getAreaCodeLevel(areaCode);
            //根据行政区划级别,获取有效行政区划代码长度
            String areaCodeLength = XzqhUtils.subXzqhDigit(areaCodeLevel);
            //截取有效的行政区划
            String realAreaCode = areaCode.substring(0, Integer.valueOf(areaCodeLength));
            vo.setAreaCode(realAreaCode);
        } else {
            vo.setAreaCode("");
        }
        String userAreaCode = tUserMapper.getUserAreaCode(vo.getUserId());
        areaCode = StrUtil.isBlank(userAreaCode) ? areaCode : userAreaCode;
        String installTableAlias = "v";
        String userTableAlias = "u";
        // 组装查询条件
        String cxtj = equipmentInfoService.getCxtjByDataRange(vo.getDataRange(), areaCode, vo.getUserId(), vo.getDepartmentId(), vo.getManufactureId(), installTableAlias, userTableAlias);
        vo.setCxtj(cxtj);

        //维修工单-查询列表或单条
        Page<RepairWorkOrderDto> page = new Page<>(vo.getPageid(), vo.getPagesize());
        List<RepairWorkOrderDto> dtos = repairWorkOrderMapper.getRepairWorkOrderInfoList(page,vo);
        for (RepairWorkOrderDto dto : dtos) {
            // 工单修完时间
            if (Objects.equals(dto.getStatus(), WorkOrderRecordDescEnum._6.getKey())) {
                Date repairDoneTime = repairWorkOrderMapper.getWorkOrderRepairDoneTime(dto.getWorkOrderId());
                dto.setRepairDoneTime(repairDoneTime);
            }
        }
        /*for (RepairWorkOrderDto dto : dtos) {
            workOrderSetParams(dto,vo.getWorkOrderCode());
        }*/
        return PageData.ok(page,dtos);
    }

    /**
     * 按id查询工单详情
     * @param vo
     * @return
     */
    @Override
    public RepairWorkOrderDto getRepairWorkOrderDetail(RepairWorkOrderVo vo) throws Exception {
        //维修工单-查询列表或单条
        Page<RepairWorkOrderDto> page = new Page<>(1, 1);
        List<RepairWorkOrderDto> dtos = repairWorkOrderMapper.getRepairWorkOrderInfoList(page,vo);
        if (CollectionUtil.isEmpty(dtos)){
            return null;
        }
        RepairWorkOrderDto dto = dtos.get(0);
        workOrderSetParams(dto,dto.getWorkOrderId());
        return dto;
    }

    // 工单获取返回值
    private void workOrderSetParams(RepairWorkOrderDto dto,String workOrderCode) {
        if (StrUtil.isNotBlank(workOrderCode)) {
            // 查询相关零件
            List<UsedPartDto> usedParts = repairWorkOrderMapper.getUsedParts(workOrderCode, Byte.valueOf(WorkOrderRecordDescEnum._6.getKey()));
            dto.setUsedParts(usedParts);
        }
        //获取每个工单的设备id和数据采集时间
        List<Map<String, String>> records = repairWorkOrderMapper.getEquipIdsAndCollectingTime(dto.getWorkOrderId());
        dto.setEquipmentInfoList(records);
        // 工单修完时间
        if (Objects.equals(dto.getStatus(), WorkOrderRecordDescEnum._6.getKey())) {
            Date repairDoneTime = repairWorkOrderMapper.getWorkOrderRepairDoneTime(dto.getWorkOrderId());
            dto.setRepairDoneTime(repairDoneTime);
        }
        //工程图处理
        String images = dto.getImages();
        if (StrUtil.isNotBlank(images)) {
            ImageDto imageDto = handleImageUrl(images);
            dto.setImagesReal(imageDto.getImagesPath());
            dto.setImagesRealBig(imageDto.getImagesRealPath());
        }
        //工程图处理
        String repairsImages = dto.getRepairsImages();
        if (StrUtil.isNotBlank(repairsImages)) {
            ImageDto imageDto = handleImageUrl(repairsImages);
            dto.setRepairsImagesReal(imageDto.getImagesPath());
            dto.setRepairsImagesRealBig(imageDto.getImagesRealPath());
        }
        //平面图处理
        String pmtImage = dto.getPmtImages();
        if (StrUtil.isNotBlank(pmtImage)) {
            ImageDto imageDto = handleImageUrl(pmtImage);
            dto.setPmtImagesReal(imageDto.getImagesPath());
            dto.setPmtImagesRealBig(imageDto.getImagesRealPath());
        }
        //设计图数据处理
        String sjtImage = dto.getSjtImages();
        if (StrUtil.isNotBlank(sjtImage)) {
            ImageDto imageDto = handleImageUrl(sjtImage);
            dto.setSjtImagesReal(imageDto.getImagesPath());
            dto.setSjtImagesRealBig(imageDto.getImagesRealPath());
        }
        //安装图数据处理
        String aztImage = dto.getAztImages();
        if (StrUtil.isNotBlank(aztImage)) {
            ImageDto imageDto = handleImageUrl(aztImage);
            dto.setAztImagesReal(imageDto.getImagesPath());
            dto.setAztImagesRealBig(imageDto.getImagesRealPath());
        }
        if (ObjectUtil.isNotNull(dto.getJd()) && ObjectUtil.isNotNull(dto.getWd()) && dto.getJd() != 0 && dto.getWd() != 0) {
            Double[] lnglat = new Double[]{dto.getJd(), dto.getWd()};
            dto.setLnglat(lnglat);
        }

        if (ObjectUtil.isNotNull(dto.getUserJd()) && ObjectUtil.isNotNull(dto.getUserWd()) && dto.getUserJd() != 0 && dto.getUserWd() != 0) {
            Double[] lnglat = new Double[]{dto.getUserJd(), dto.getUserWd()};
            dto.setUserLnglat(lnglat);
        }
    }

    /**
     * 工单跟踪记录-查询列表
     *
     * @param
     * @return
     */
    @Override
    public List<WorkOrderFollowUpRecordDto> getWorkOrderFollowUpRecordsById(String workOrderId) {
        List<WorkOrderFollowUpRecordDto> list = repairWorkOrderMapper.getWorkOrderFollowUpRecordsById(workOrderId);
        return list;
    }

    /**
     * 添加工单
     * @param vo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addFaultWorkOrder(FaultWorkOrderVo vo) throws Exception{
        String faultCode = null;
        List<EquipmentFaultInfoListDto> faultInfoList = null;
        if (StrUtil.isNotBlank(vo.getFaultId())) {
            //根据故障id获取设备故障
            Page<EquipmentFaultInfoListDto> page = new Page<>(1, 1); // 查询第一页第一条
            EquipmentFaultInfoListVo faultVo = new EquipmentFaultInfoListVo();
            faultVo.setFaultId(vo.getFaultId());
            faultInfoList = equipmentFaultInfoMapper.getEquipmentFaultInfoList(page,faultVo);
            if (CollUtil.isNotEmpty(faultInfoList)) {
                faultCode = faultInfoList.get(0).getGzms(); // TODO: 2024/3/11 暂时先用故障描述
            }
        }
        //如果没有传入师傅到目的地的距离, 调用高德api查询
        if ((vo.getDistance() == null || vo.getDistance() == 0) && StrUtil.isNotBlank(vo.getMaintainId()) && StrUtil.isNotBlank(vo.getLocationId())) {
            String userId = vo.getMaintainId();
            String locationId = vo.getLocationId();
            //获取经纬度
            Map<String, String> originCoordinate = tUserMapper.getCoordinateByUserId(userId);
            Map<String, String> destinationCoordinate = tUserMapper.getCoordinateByLocationId(locationId);

            String originLng = "";
            String originLat = "";
            if (CollUtil.isNotEmpty(originCoordinate)) {
                originLng = originCoordinate.getOrDefault("lng", "");
                originLat = originCoordinate.getOrDefault("lat", "");
            }
            String destinationLng = "";
            String destinationLat = "";
            if (CollUtil.isNotEmpty(destinationCoordinate)) {
                destinationLng = destinationCoordinate.getOrDefault("lng", "");
                destinationLat = destinationCoordinate.getOrDefault("lat", "");
            }
            Integer distance = MapUtils.getDistanceBetweenOriginNDestination(originLat, originLng, destinationLat, destinationLng);
            if (distance != null && distance > 0) {
                vo.setDistance(distance / 1000);
            }
        }
        //1.创建维修工单
        IsWorkOrderInfo workOrderInfo = new IsWorkOrderInfo();
        String workOrderId = AgentIdUtils.createID(AgentIdEnum._work_order_info);
        workOrderInfo.setWorkOrderId(workOrderId);
        workOrderInfo.setManufactureId(vo.getManufactureId());
        workOrderInfo.setDdId(vo.getLocationId());
        workOrderInfo.setUserId(vo.getUserId());
        workOrderInfo.setContact(vo.getContact());
        workOrderInfo.setContactPhone(vo.getPhone());
        workOrderInfo.setAddress(vo.getAddress());
        workOrderInfo.setDesc(vo.getFaultInfo());
        if (StrUtil.isBlank(vo.getAreaCode()) && StrUtil.isNotBlank(vo.getLocationId())) {
            String areaCode = tXzqhMapper.getAreaCodeByLocationId(vo.getLocationId());
            vo.setAreaCode(areaCode);
        }
        workOrderInfo.setXzqhdm(vo.getAreaCode());
        if (StrUtil.isNotEmpty(faultCode)) {
            workOrderInfo.setErroCode(faultCode);
        }
        workOrderInfo.setBxsj(vo.getReportTime());
        workOrderInfo.setGdlx(vo.getWordOrderType());
        workOrderInfo.setGddj(vo.getWorkOrderLevel());
        workOrderInfo.setClsx(vo.getProcessTimeLimit());
        if (StrUtil.isNotBlank(vo.getMaintainId())) {
            if (StrUtil.isBlank(vo.getMaintainPhone())) {
                throw new Exception("业务支持人员电话不能为空");
            }
            if (ObjectUtil.isNull(vo.getIfSendSms())) {
                throw new Exception("是否发送短信不能为空");
            }
            workOrderInfo.setMaintainId(vo.getMaintainId());
            // 0:创建工单;1:待分配;2:待接单   0:待处理，1：待接单
            workOrderInfo.setStatus((byte) 1);
        } else {
            workOrderInfo.setStatus((byte) 0);
        }
        //工单来源:0:安装工单;1.用户保修工单;2.故障生成工单
        workOrderInfo.setHandleMode(vo.getWorkOrderSource().byteValue());
        workOrderInfo.setSfsc((byte) 0);
        workOrderInfo.setSjly(sjly);
        //派单审核人
        workOrderInfo.setOrderdirectorid(vo.getOrderDirectorId());
        if (ObjectUtil.isNotNull(vo.getDistance())) {
            workOrderInfo.setDistance(vo.getDistance());
        }
        //根据故障创建维修工单
        int res = repairWorkOrderMapper.insert(workOrderInfo);
        if (res > 0) {
            //根据维修工单id 创建工单设备关联关系
            IsWorkOrderEquipmentInfo workOrderEquipmentInfo = new IsWorkOrderEquipmentInfo();
            //关系id
            workOrderEquipmentInfo.setRelationId(AgentIdUtils.createID(AgentIdEnum._work_order_equipment_info));
            workOrderEquipmentInfo.setWorkOrderId(workOrderId);
            workOrderEquipmentInfo.setSbId(vo.getEquipmentId());
            workOrderEquipmentInfo.setSjly(sjly);
            //创建工单设备关联关系
            int workEquipment = workOrderIsEquipmentInfoMapper.insert(workOrderEquipmentInfo);
            if (workEquipment > 0) {
                //3.创建工单记录
                IsWorkOrderRecord workOrderRecord = new IsWorkOrderRecord();
                workOrderRecord.setRecordId(AgentIdUtils.createID(AgentIdEnum._work_order_record));
                workOrderRecord.setManufactureId(vo.getManufactureId());
                workOrderRecord.setWorkOrderId(workOrderId);
                workOrderRecord.setUserId(vo.getUserId());
                workOrderRecord.setSjly(sjly);
                workOrderRecord.setMaintainId(vo.getMaintainId());
                workOrderRecord.setStatus(Byte.parseByte(WorkOrderRecordDescEnum._0.getKey()));
                workOrderRecord.setDesc(WorkOrderRecordDescEnum._0.getVal());
                //创建工单记录
                int createWorkRecord = isWorkOrderRecordMapper.insert(workOrderRecord);
                //分配工单
                int handleWorkRecord = 1;
                if (StrUtil.isNotBlank(vo.getMaintainId())) {
                    workOrderRecord.setId(null);
                    workOrderRecord.setRecordId(AgentIdUtils.createID(AgentIdEnum._work_order_record));
                    workOrderRecord.setMaintainId(vo.getMaintainId());
                    workOrderRecord.setStatus(Byte.parseByte(WorkOrderRecordDescEnum._1.getKey()));
                    workOrderRecord.setDesc(WorkOrderRecordDescEnum._1.getVal());
                    //创建工单记录
                    handleWorkRecord = isWorkOrderRecordMapper.insert(workOrderRecord);
                }
                if (createWorkRecord <= 0 || handleWorkRecord <= 0) {
                    throw new Exception("创建工单记录失败");
                } else {
                    if (StrUtil.isNotBlank(vo.getOrderDirectorId())) {
                        messageInfoService.pushAssignNotification(vo.getOrderDirectorId(), workOrderId);
                    }
                    if (StrUtil.isNotBlank(vo.getMaintainId())) {
                        messageInfoService.pushNewWorkOrderNotification(vo.getMaintainId(), workOrderId);
                    }
                }
            } else {
                throw new Exception("创建工单设备关联失败");
            }
        } else {
            throw new Exception("创建工单失败");
        }
        //4.修改故障信息
        if (CollUtil.isNotEmpty(faultInfoList)) {
            equipmentFaultInfoMapper.updateFaultInfoAfterCreateWorkOrder(vo.getFaultId(), workOrderId);
        }
        return workOrderId;
    }

    /**
     * 修改工单
     * @param workOrderId
     */
    @Override
    public void updateReportWorkOrder(String workOrderId) {

    }

    /**
     * 处理图片地址
     *
     * @param images
     * @return
     */
    public ImageDto handleImageUrl(String images) {
        ImageDto imageDto = new ImageDto();
        List<String> imagePath = OssImagePathUtils
                .getSomeImgSignURL(images, 1, endpoint, accessKeyId, accessKeySecret, bucketName);
        List<String> imageRealPath = OssImagePathUtils
                .getSomeImgSignURL(images, 2, endpoint, accessKeyId, accessKeySecret, bucketName);

        imageDto.setImagesPath(imagePath);
        imageDto.setImagesRealPath(imageRealPath);

        return imageDto;
    }
}
